/**
 * 响应式设计工具函数
 */

import { ref, computed, onMounted, onUnmounted, watch, type ComputedRef } from 'vue';

// 断点定义
export const breakpoints = {
  xs: 480,    // 超小屏幕 (手机)
  sm: 768,    // 小屏幕 (大手机)
  md: 992,    // 中等屏幕 (平板)
  lg: 1200,   // 大屏幕 (小桌面)
  xl: 1920,   // 超大屏幕 (桌面)
} as const;

export type Breakpoint = keyof typeof breakpoints;

/**
 * 使用断点检测
 */
export function useBreakpoint() {
  const width = ref(window.innerWidth);
  
  const isXs = computed(() => width.value <= breakpoints.xs);
  const isSm = computed(() => width.value <= breakpoints.sm);
  const isMd = computed(() => width.value <= breakpoints.md);
  const isLg = computed(() => width.value <= breakpoints.lg);
  const isXl = computed(() => width.value > breakpoints.lg);
  
  const currentBreakpoint = computed<Breakpoint>(() => {
    if (isXs.value) return 'xs';
    if (isSm.value) return 'sm';
    if (isMd.value) return 'md';
    if (isLg.value) return 'lg';
    return 'xl';
  });
  
  const updateWidth = () => {
    width.value = window.innerWidth;
  };
  
  onMounted(() => {
    window.addEventListener('resize', updateWidth);
  });
  
  onUnmounted(() => {
    window.removeEventListener('resize', updateWidth);
  });
  
  return {
    width,
    isXs,
    isSm,
    isMd,
    isLg,
    isXl,
    currentBreakpoint,
  };
}

/**
 * 使用屏幕尺寸信息
 */
export interface ScreenSize {
  isMobile: ComputedRef<boolean>;
  isTablet: ComputedRef<boolean>;
  isDesktop: ComputedRef<boolean>;
  dialogWidth: ComputedRef<string>;
  formGrid: ComputedRef<number>;
  tableMinWidth: ComputedRef<number>;
}

export function useScreenSize(): ScreenSize {
  const { isSm, isMd } = useBreakpoint();
  
  const isMobile = computed(() => isSm.value);
  const isTablet = computed(() => !isSm.value && isMd.value);
  const isDesktop = computed(() => !isMd.value);
  
  const dialogWidth = computed(() => {
    if (isMobile.value) return '95%';
    if (isTablet.value) return '85%';
    return '80%';
  });
  
  const formGrid = computed(() => {
    if (isMobile.value) return 1;
    if (isTablet.value) return 2;
    return 3;
  });
  
  const tableMinWidth = computed(() => {
    if (isMobile.value) return 400;
    if (isTablet.value) return 600;
    return 800;
  });
  
  return {
    isMobile,
    isTablet,
    isDesktop,
    dialogWidth,
    formGrid,
    tableMinWidth,
  };
}

/**
 * 防抖函数
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useDebounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): T {
  let timeoutId: number;
  
  return ((...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = window.setTimeout(() => fn(...args), delay);
  }) as T;
}

/**
 * 节流函数
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useThrottle<T extends (...args: any[]) => any>(
  fn: T,
  limit: number
): T {
  let inThrottle: boolean;
  
  return ((...args: Parameters<T>) => {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  }) as T;
}

/**
 * 响应式字体大小
 */
export function useResponsiveFontSize() {
  const { isSm } = useBreakpoint();
  
  const fontSize = computed(() => isSm.value ? '14px' : '16px');
  
  return {
    fontSize,
  };
}

/**
 * 响应式边距
 */
export function useResponsiveSpacing() {
  const { isSm, isMd } = useBreakpoint();
  
  const spacing = computed(() => {
    if (isSm.value) return 8;
    if (isMd.value) return 16;
    return 24;
  });
  
  return {
    spacing,
  };
}

/**
 * 响应式图片
 */
export interface ResponsiveImage {
  src: string;
  srcset?: string;
  sizes?: string;
  alt: string;
  className?: string;
}

export function createResponsiveImage(
  baseUrl: string,
  widths: number[] = [400, 800, 1200],
  format: string = 'webp'
): ResponsiveImage {
  const srcset = widths
    .map(width => `${baseUrl}-${width}.${format} ${width}w`)
    .join(', ');
  
  const sizes = widths
    .map((width, index) => {
      const breakpoint = index === 0 ? breakpoints.sm : breakpoints.md;
      return `(max-width: ${breakpoint}px) ${width}px`;
    })
    .concat(`${widths[widths.length - 1]}px`)
    .join(', ');
  
  return {
    src: `${baseUrl}-${widths[0]}.${format}`,
    srcset,
    sizes,
    alt: '',
  };
}

/**
 * 响应式网格列数
 */
export function useResponsiveGrid(
  mobileColumns: number = 1,
  tabletColumns: number = 2,
  desktopColumns: number = 3,
  largeDesktopColumns: number = 4
) {
  const { isSm, isMd, isLg } = useBreakpoint();
  
  const columns = computed(() => {
    if (isSm.value) return mobileColumns;
    if (isMd.value) return tabletColumns;
    if (isLg.value) return desktopColumns;
    return largeDesktopColumns;
  });
  
  return {
    columns,
  };
}

/**
 * 响应式表单布局
 */
export interface FormLayout {
  grid: ComputedRef<number>;
  gap: ComputedRef<number>;
  labelWidth: ComputedRef<string>;
}

export function useResponsiveFormLayout(): FormLayout {
  const { isSm, isMd } = useBreakpoint();
  
  const grid = computed(() => {
    if (isSm.value) return 1;
    if (isMd.value) return 2;
    return 3;
  });
  
  const gap = computed(() => {
    if (isSm.value) return 12;
    if (isMd.value) return 16;
    return 20;
  });
  
  const labelWidth = computed(() => {
    if (isSm.value) return '100%';
    if (isMd.value) return '120px';
    return '140px';
  });
  
  return {
    grid,
    gap,
    labelWidth,
  };
}

/**
 * 检测触摸设备
 */
export function useTouchDevice() {
  const isTouch = ref(false);
  
  onMounted(() => {
    isTouch.value = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
  });
  
  return {
    isTouch,
  };
}

/**
 * 检测暗黑模式
 */
export function useDarkMode() {
  const isDark = ref(false);
  
  const checkDarkMode = () => {
    isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
  };
  
  onMounted(() => {
    checkDarkMode();
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', checkDarkMode);
  });
  
  onUnmounted(() => {
    window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', checkDarkMode);
  });
  
  return {
    isDark,
  };
}

/**
 * 响应式工具类生成器
 */
export const responsiveUtils = {
  /**
   * 生成响应式 padding 类
   */
  padding: (size: 'sm' | 'md' | 'lg' = 'md') => {
    const sizes = {
      sm: { mobile: '8px', tablet: '12px', desktop: '16px' },
      md: { mobile: '12px', tablet: '16px', desktop: '24px' },
      lg: { mobile: '16px', tablet: '24px', desktop: '32px' },
    };
    
    return sizes[size];
  },
  
  /**
   * 生成响应式 margin 类
   */
  margin: (size: 'sm' | 'md' | 'lg' = 'md') => {
    const sizes = {
      sm: { mobile: '8px', tablet: '12px', desktop: '16px' },
      md: { mobile: '12px', tablet: '16px', desktop: '24px' },
      lg: { mobile: '16px', tablet: '24px', desktop: '32px' },
    };
    
    return sizes[size];
  },
  
  /**
   * 生成响应式字体大小
   */
  fontSize: (size: 'sm' | 'md' | 'lg' | 'xl' = 'md') => {
    const sizes = {
      sm: { mobile: '12px', tablet: '13px', desktop: '14px' },
      md: { mobile: '14px', tablet: '15px', desktop: '16px' },
      lg: { mobile: '16px', tablet: '18px', desktop: '20px' },
      xl: { mobile: '18px', tablet: '20px', desktop: '24px' },
    };
    
    return sizes[size];
  },
};

/**
 * 响应式事件监听器
 */
export function useResponsiveEventListener(
  event: string,
  handler: EventListener,
  options?: AddEventListenerOptions
) {
  const shouldListen = computed(() => {
    // 根据屏幕尺寸决定是否监听事件
    return true; // 可根据业务需求调整
  });
  
  onMounted(() => {
    if (shouldListen.value) {
      window.addEventListener(event, handler, options);
    }
  });
  
  onUnmounted(() => {
    window.removeEventListener(event, handler, options);
  });
  
  watch(shouldListen, (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (newValue) {
        window.addEventListener(event, handler, options);
      } else {
        window.removeEventListener(event, handler, options);
      }
    }
  });
  
  return {
    shouldListen,
  };
}

/**
 * 响应式 CSS 变量生成器
 */
export function useResponsiveCSSVariables() {
  const { isSm, isMd } = useBreakpoint();
  
  const variables = computed(() => {
    return {
      '--responsive-padding': isSm.value ? '8px' : isMd.value ? '12px' : '16px',
      '--responsive-margin': isSm.value ? '8px' : isMd.value ? '12px' : '16px',
      '--responsive-font-size': isSm.value ? '14px' : '16px',
      '--responsive-border-radius': isSm.value ? '4px' : '8px',
    };
  });
  
  return {
    variables,
  };
}